
program ivclust2 
version 9

/*2sls estimation with 2-way clustering with two endogenous variables*/

syntax anything [if] [in] [aweight fweight iweight pweight /], cluster(string) [*]

quietly {

tokenize `cluster'

xi:ivreg `anything' `if', cluster (`1')
gen numobs=e(N)
mat dd=e(b)
mat ddd=dd[1,1]
mat ddd2=dd[1,2]
svmat ddd, names(coef)
svmat ddd2, names(coeff)
mat vv=e(V)
mat vvv=vv[1,1]
mat vvv2=vv[2,2]
svmat vvv, names(var)
svmat vvv2, names(varr)
matrix drop dd ddd vv vvv ddd2 vvv2
rename coef1 cssa 
rename var1 vara
rename coeff1 cage_iq 
rename varr1 varra

xi:ivreg `anything' `if', cluster (`2') 
mat vv=e(V)
mat vvv=vv[1,1]
mat vvv2=vv[2,2]
svmat vvv, names(var)
svmat vvv2, names(varr)
matrix drop vv vvv vvv2
rename var1 varb
rename varr1 varrb

xi:ivreg `anything' `if', cluster (`3') 
mat vv=e(V)
mat vvv=vv[1,1]
mat vvv2=vv[2,2]
svmat vvv, names(var)
svmat vvv2, names(varr)
matrix drop vv vvv vvv2
rename var1 varc
rename varr1 varrc

gen truese_ssa=sqrt(vara+varb-varc)
gen truese_age=sqrt(varra+varrb-varrc)
drop vara varb varc varra varrb varrc 
}


su numobs cssa cage_iq truese_ssa truese_age
drop numobs cssa cage_iq truese_ssa truese_age 


end

 
